const app = new Vue({
    el: '#app',
    data() {
        // 校验学号是否存在
        const rulesSNo = (rule, value, callback) => {
            if (this.isEdit) {
                callback();
            }
            // 使用Axios
            axios.post(
                this.baseURL + 'sno/check/',
                {
                    sno: value,
                }
            )
                .then((res) => {
                    // 请求成功
                    if (res.data.code === 1) {
                        if (res.data.exists) {
                            callback(new Error('学号已存在'))
                        } else {
                            callback();
                        }
                    } else {
                        callback(new Error('效验学号后端出现异常'))
                    }
                })
                .catch((err) => {
                    console.log(err)
                });
        }

        return {
            students: [],
            pageStudents: [],
            baseURL: 'http://127.0.0.1:8000/',
            inputStr: '',
            selectStudents: [],

            total: 0,
            currentpage: 1,
            pagesize: 10,


            // 
            dialogVisible: false,
            dialogTitle: '',
            isView: false,
            isEdit: false,

            studentForm: {
                sno: '',
                name: '',
                gender: '',
                birthday: '',
                mobile: '',
                email: '',
                address: '',
                image: '',
                imageUrl: '',
            },
            rules: {
                sno: [
                    { required: true, message: '学号不能为空', trigger: 'blur' },
                    { pattern: /^[9][5]\d{3}$/, message: '学号必须是95开头的5位数', trigger: 'blur' },
                    { validator: rulesSNo, trigger: 'blur' },
                ],
                name: [
                    { required: true, message: '姓名不能为空', trigger: 'blur' },
                    { pattern: /^[\u4e00-\u9fa5]{2,5}$/, message: '姓名必须是2-5个汉字', trigger: 'blur' }
                ],
                gender: [
                    { required: true, message: '性别不能为空', trigger: 'change' },

                ],
                birthday: [
                    { required: true, message: '出生日期不能为空', trigger: 'change' },

                ],
                mobile: [
                    { required: true, message: '手机号不能为空', trigger: 'blur' },
                    { pattern: /^[1][35789]\d{9}$/, message: '手机号必须要符合规范', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '邮箱地址不能为空', trigger: 'blur' },
                    { pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, message: '邮箱地址必须要符合规范', trigger: 'blur' },
                ],
                address: [
                    { required: true, message: '家庭地址不能为空', trigger: 'blur' },

                ]
            }
        }
    },
    mounted() {
        this.getStudents();
    },
    methods: {
        getStudents: function () {
            let that = this
            axios
                .get(this.baseURL + 'students/')
                .then(function (res) {
                    if (res.data.code === 1) {
                        that.students = res.data.data;
                        // 获取返回的行数
                        that.total = res.data.data.length;
                        that.getPageStudents();
                        that.$message({
                            message: '数据加载成功',
                            type: 'success'
                        });
                    } else {
                        that.$message.error(res.data.msg);
                    }
                })
                .catch(function (err) {
                    console.log(err);
                })
        },
        getAllStudents() {
            this.inputStr = '';
            // 获取所有
            this.getStudents();
        },
        // 添加学生打开
        addStudent() {
            this.dialogTitle = '添加信息'
            this.dialogVisible = true;
        },
        // 
        getImageBySno(sno) {
            for (oneStudent of this.students) {
                if (oneStudent.sno == sno) {
                    return oneStudent.image;
                }
            }
        },
        // 
        updateStudent(row) {
            this.dialogTitle = '修改信息'

            this.isEdit = true;

            this.dialogVisible = true;

            this.studentForm = JSON.parse(JSON.stringify(row));

            this.studentForm.image = this.getImageBySno(row.sno)
            this.studentForm.imageUrl = this.baseURL + 'media/' + this.studentForm.image;
        },
        // 提交学生的表单
        submitStudentForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    // 效验成功  添加  修改
                    if (this.isEdit) {
                        // 修改
                        this.submitUpdateStudent();
                    } else {
                        // 添加
                        this.submitAddStudent();
                    }
                } else {
                    console.log('error submit!!')
                    return false;
                }
            });

        },
        // 添加到数据库
        submitAddStudent() {
            // 定义that
            let that = this;
            // 执行
            axios
                .post(that.baseURL + 'student/add/', that.studentForm)
                .then(res => {
                    // 执行成功
                    if (res.data.code === 1) {
                        that.students = res.data.data;
                        that.total = res.data.data.length;
                        that.getPageStudents();
                        that.$message({
                            message: '查询数据加载成功',
                            type: 'success'
                        });
                        // g关闭
                        that.closeDialogForm('studentForm')
                    } else {
                        that.$message.error(res.data.msg);
                    }
                })
                .catch(err => {
                    // 执行失败
                    console.log(err);
                    that.$message.error('获取后端查询结果出现异常')
                })
        },
        // 修改更新数据库
        submitUpdateStudent() {
            // 定义that
            let that = this;
            // 执行
            axios
                .post(that.baseURL + 'student/update/', that.studentForm)
                .then(res => {
                    // 执行成功
                    if (res.data.code === 1) {
                        that.students = res.data.data;
                        that.total = res.data.data.length;
                        that.getPageStudents();
                        that.$message({
                            message: '数据修改成功',
                            type: 'success'
                        });
                        // g关闭
                        that.closeDialogForm('studentForm')
                    } else {
                        that.$message.error(res.data.msg);
                    }
                })
                .catch(err => {
                    // 执行失败
                    console.log(err.getTime());
                    that.$message.error('修改时获取后端查询结果出现异常')
                })
        },
        // 删除
        deleteStudent(row) {
            // 等待确认
            this.$confirm('是否确认删除学生信息【学号：' + row.sno + ' \t姓名: ' + row.name + '】, 信息', '提示', {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let that = this
                axios.post(that.baseURL + 'student/delete/', { sno: row.sno })
                    .then(res => {
                        if (res.data.code === 1) {
                            that.students = res.data.data;
                            that.total = res.data.data.length;
                            that.getPageStudents();
                            that.$message({
                                message: '数据删除成功',
                                type: 'success'
                            })
                        } else {
                            that.$message.error(res.data.msg);
                        }
                    })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });

        },
        // 批量删除
        deleteStudents() {
            // 等待确认
            this.$confirm('是否确认批量删除' + this.selectStudents.length + '个学生信息', '提示', {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let that = this
                axios.post(that.baseURL + 'students/delete/', { student: that.selectStudents })
                    .then(res => {
                        if (res.data.code === 1) {
                            that.students = res.data.data;
                            that.total = res.data.data.length;
                            that.getPageStudents();
                            that.$message({
                                message: '数据删除成功',
                                type: 'success'
                            })
                        } else {
                            that.$message.error(res.data.msg);
                        }
                    })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });

        },
        // 
        closeDialogForm(formName) {
            this.$refs[formName].resetFields();
            this.studentForm.sno = '';
            this.studentForm.name = '';
            this.studentForm.gender = '';
            this.studentForm.birthday = '';
            this.studentForm.mobile = '';
            this.studentForm.emai = '';
            this.studentForm.address = '';
            this.studentForm.image = '';
            this.studentForm.imageUrl = '';
            this.dialogVisible = false;
            this.isEdit = false;
            this.isView = false;
        },
        // 头像
        uploadPicturePost(file) {
            let that = this;

            let fileReq = new FormData();

            fileReq.append('avatar', file.file);

            axios(
                {
                    method: 'post',
                    url: that.baseURL + 'upload/',
                    data: fileReq
                }
            ).then(res => {
                if (res.data.code === 1) {
                    that.studentForm.image = res.data.name;
                    that.studentForm, imageUrl = that.baseURL + 'media/' + res.data.name;
                } else {
                    that.$message.error(res.data.msg)
                }

            }).catch(err => {
                console.log(err)
                that.$message.error('上传头像出现异常')
            })
        },
        viewStudent(row) {
            this.dialogTitle = '查看信息'
            this.isView = true;
            this.dialogVisible = true;
            // console.log(row)
            // 赋值
            // this.studentForm = row;
            this.studentForm = JSON.parse(JSON.stringify(row));

            this.studentForm.image = this.getImageBySno(row.sno)
            this.studentForm.imageUrl = this.baseURL + 'media/' + this.studentForm.image;

        },
        // 获取当前页的 学生数据
        getPageStudents() {
            // 清空pageStudents 数据
            this.pageStudents = [];
            // 获得当前页面的数据
            for (let i = (this.currentpage - 1) * this.pagesize; i < this.total; i++) {
                // 遍历数据添加
                this.pageStudents.push(this.students[i]);
                // 判断是否是一页的要求
                if (this.pageStudents.length === this.pagesize) break;
            }
        },
        // 实现学生信息查询
        queryStudents() {
            // 使用ajax请求     post      传递InputStr
            let that = this
            // 开始ajax请求
            axios
                .post(
                    that.baseURL + 'students/query/',
                    {
                        inputstr: that.inputStr
                    }
                )
                .then(function (res) {
                    if (res.data.code === 1) {
                        that.students = res.data.data;
                        that.total = res.data.data.length;
                        that.getPageStudents();
                        that.$message({
                            message: '查询数据加载成功',
                            type: 'success'
                        });
                    } else {
                        that.$message.error(res.data.msg)
                    }
                })
                .catch(function (err) {
                    console.log(err);
                    that.$message.error('获取后端查询结果出现异常')
                });
        },
        // 分页的排序
        handleSizeChange(size) {
            // 修改当前页的行数
            this.pagesize = size
            this.getPageStudents();
        },
        // 调整当前页的页码
        handleCurrentChange(pageNumber) {
            this.currentpage = pageNumber
            this.getPageStudents();
        },
        // 
        handleSelectionChange(data) {
            this.selectStudents = data;
            console.log(data);
        },

    }
})
